<?php

namespace App\Helpers;

class Map
{
    private $url = "https://apis.map.qq.com/ws/geocoder/v1/?address=";

    private $key;

    private $address;

    public function __construct()
    {
        $this->key = env('MAP_KEY','CBABZ-3YVKD-KLS45-P5IQC-JANCQ-IHBIN');
    }

    public function getLocation($address)
    {
        $this->setAddress($address);
        if($res = $this->get()){
            $res = is_string($res)?json_decode($res,true):$res;
            if ($res['status'] == 0){
                return $res['result']['location'];
            }
        }
        return false;
    }

    public function search($address)
    {
        $this->setAddress($address);
        return $this->get();
    }

    public function get()
    {
        $url = $this->format_url();
        return $this->http_get($url);
    }

    public function setAddress($address)
    {
        $this->address = $address;
    }

    public function format_url()
    {
        return $this->url.$this->address.'&key='.$this->key;
    }

    public function http_get($url)
    {
        try {
            //初始化
            $curl = curl_init();
            //设置抓取的url
            curl_setopt($curl, CURLOPT_URL, $url);
            //设置头文件的信息作为数据流输出
            //curl_setopt($curl, CURLOPT_HEADER, 1);
            //设置获取的信息以文件流的形式返回，而不是直接输出。
            curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
            //执行命令
            $data = curl_exec($curl);
            //关闭URL请求
            curl_close($curl);
            //返回获得的数据
            return $data;
        } catch (\Exception $e) {
            Helpers::log($e->getMessage(),'map');
        }
        return false;
    }
}
